//app.js
const qcloud = require("./vendor/wafer2-client-sdk/index");
const config = require("./utils/config");
const util = require("./utils/util.js");
const api = require("./utils/api.js");
const tool = require("./utils/common.js");
const localStorage = require("./utils/localStorage.js")

App({
  /**
   * 全局变量
   */
  globalData: {
    userInfo: {
      defaultCity: "灵宝市",
      defaultCounty: "湖滨区",
      currentLatitude: "",
      currentLongitude: ""
    },
    iphoneInfo: {},
    address: {},
    usrePortrait: "",
    weatherData: "",
    air: "",
    day: ""
  },

  onLaunch: function(res) {
    // 挂载变量到wx上
    wx.$localStorage = localStorage;
    wx.$tool = tool;
    wx.$util = util;
    wx.$api = api;

    // 获取参数
    tool.checkPageParameter(res);

    // 判断是否由分享进入小程序
    if (res.scene == 1007 || res.scene == 1008) {
      this.globalData.isShareInto = true
    } else {
      this.globalData.isShareInto = false
    };
    // sdk文件分析
    // qcloud.setLoginUrl(config.service.loginUrl)

    this.appLogin();

    // 初始化 网络单例  当网络发生变化就会回调
    this.dynamicNetWorking().then(res => {
      if (res) {
        // var obj = { ...user, ...val };

      }
    });
    // 初始化 全局信息
    this.initModelInfo();
    this.appIsUptate();
  },

  /**
   * 动态监听 网络
   */
  dynamicNetWorking: function() {
    var promise = new Promise((resolve, reject) => {
      wx.onNetworkStatusChange(function(res) {
        if (res.networkType == "none" || res.networkType == "unknown") {
          util.showModel("网络异常", "请检查当前网络是否可用");
          reject(false);
        } else {
          resolve(true);
        }
      });
    });
    return promise;
  },
  /**
   * 获取 code进行登录
   */
  appLogin() {
    wx.login({
      success: function(res) {
        console.log('成功获取 code' + res.code)
        let obj = {
          code: res.code
        };
        wx.$api.getOpenId(obj).then(res => {
          console.log(res.data.data.token)
          wx.$localStorage.set('logintoekn', res.data.data.token)
          
        })
      }
    })
  },
  /**
   * 初始化单例
   */
  initModelInfo() {
    // 获取当前日期
    this.globalData.day = util.formatTime(new Date()).split(" ")[0];
    this.getCurrentIphoneInfo();
    this.getLocation();
  },
  getCurrentIphoneInfo() {
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.globalData.iphoneInfo = res;
        // 根据 model 进行判断 手机型号
        if (res.model.search('iPhone X') != -1) {
          that.globalData.isIPX = true
        }
      }
    });
  },
  /**
   * 定位当前城市的函数
   */
  getLocation: function() {
    console.log("正在定位城市");
    var that = this;
    wx.getLocation({
      type: "wgs84",
      success: function(res) {
        //当前的经度和纬度
        that.globalData.userInfo.currentLatitude = res.latitude;
        that.globalData.userInfo.currentLongitude = res.longitude;
        // 获取当前位置信息
        that.getcurrentLocationInfo(res)
      },
      fail: function(res) {
        console.log(res);
        util.showToast("获取当前位置失败");
      }
    });
  },
  getcurrentLocationInfo(pram) {
    var that = this;
    var qqMapApi = 'https://apis.map.qq.com/ws/geocoder/v1/' //地图接口链接
    // 获取当前地址信息
    qqMapApi = qqMapApi + "?location=" + pram.latitude + ',' +
      pram.longitude + "&key=" + config.key + "&get_poi=1";
    wx.request({
      url: qqMapApi,
      data: {},
      method: 'GET',
      success: (res) => {
        console.log(res)
        if (res.statusCode == 200 && res.data.status == 0) {
          that.globalData.address.component = res.data.result.address_component;
          that.globalData.address.address = res.data.result.address
          that.globalData.address.pois = res.data.result.pois;
        }
      }
    })
  },
  /**
   * 小程序更新操作
   */
  appIsUptate: function() {
    const updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function(res) {
      // 请求完新版本信息的回调
      console.log("版本信息 是否需要更新 ：" + res.hasUpdate);
    });

    updateManager.onUpdateReady(function() {
      wx.showModal({
        title: "更新提示",
        content: "新版本已经准备好，是否重启应用？",
        success: function(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate();
          }
        }
      });
    });

    updateManager.onUpdateFailed(function() {
      // 新的版本下载失败
      util.showModal("更新提示", "新版本下载失败");
    });
  }
});